package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.LogInfoMapper;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;

public class CheckedPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private LogInfoMapper logInfoMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //对动态资源进行操作
        if (handler instanceof HandlerMethod){
            //获取员工对象判断是否是管理员
            Employee emp = UserContext.getCurrentUser();
            //判断是否是管理员,是则放行
            if (emp.isAdmin()){
                return true;
            }
            //获取员工的权限
            //TODO 从session域中获取权限集合
            List<Permission> permissions = UserContext.getCurrentPermissions();
            //获取请求方法
            Method method = ((HandlerMethod) handler).getMethod();
            //判断方法上是否贴了RequiredPermission注解（上了权限）
            RequiredPermission methodAnnotation = method.getAnnotation(RequiredPermission.class);
            //如果expression等于空，证明该请求没有权限,直接放行
            if (methodAnnotation==null){
                return true;
            }
            //如果运行到这，证明该请求上了权限
            //获取权限表达式
            String expression = methodAnnotation.expression();
            //遍历员工的权限集合，判断是否含有该权限,如果含有直接放行
            for (Permission p : permissions){
                if (p.getExpression().equals(expression)){
                    return true;
                }
            }
            //对没有权限进行处理
            //判断请求是js数据还是请求转发
            ResponseBody annotation = method.getAnnotation(ResponseBody.class);
            if (annotation!=null){
                //设置响应格式
                response.setContentType("application/json;charset=utf-8");
                //把JsonResult转成js对象
                String msg = "没有权限访问";
                String uuid = UserContext.getUUID();
                logInfoMapper.updateErrorByUUID(msg,uuid);
                String jsonString = JSON.toJSONString(new JsonResult("你没有权限访问喔！", false));
                response.getWriter().write(jsonString);
            }else {
                //对请求也面进行处理
                String msg = "没有权限访问";
                String uuid = UserContext.getUUID();
                logInfoMapper.updateErrorByUUID(msg,uuid);
                response.sendRedirect("/nopermission");
            }
            return false;
        }
        return true;
    }
}
